package com.zhiche.lisa.mdm.service.impl;

import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.IOUtil.UriIOUtil;
import com.zhiche.lisa.core.utils.excel.ExportExcelUtil;
import com.zhiche.lisa.core.utils.excel.ImportExcelUtil;
import com.zhiche.lisa.core.utils.excel.RangeXlsTemplate;
import com.zhiche.lisa.core.utils.geo.BaiDuMap.util.BaiDuMapRouteUtil;
import com.zhiche.lisa.core.utils.qiniu.config.QiniuConfig;
import com.zhiche.lisa.core.utils.qiniu.domain.QuniuResponse;
import com.zhiche.lisa.core.utils.qiniu.util.QiniuUtils;
import com.zhiche.lisa.mdm.dao.model.RangeCalcLog;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class RangeCalcServiceImpl {

    private static final Logger LOGGER = LoggerFactory.getLogger(RangeCalcServiceImpl.class);

    @Autowired
    private QiniuConfig qiniuConfig;

    @Autowired
    private RangeCalcLogServiceImpl rangeCalcLogService;

    /**
     * 后端上传文件到七牛
     * @param file
     * @return
     */
    private Long SaveUpLoadFileToQiniu(File file){
        Long id = 0L;
        try{
            String key = "template/" + file.getName();
            QuniuResponse quniuResponse = QiniuUtils.uploadFile(file,key);
            if(Objects.nonNull(quniuResponse)){
                RangeCalcLog rangeCalcLog = new RangeCalcLog();
                rangeCalcLog.setUploadFileName(key);
                rangeCalcLog.setGmtUpload(new Date());
                rangeCalcLogService.insert(rangeCalcLog);
                id = rangeCalcLog.getId();
            }
        }
        catch (Exception ex){
             throw new BaseException(ex.getMessage());
        }
        return id;
    }


    /**
     * 导入并计算
     * @param multipartFile
     */
    public Long importRange(MultipartFile multipartFile) {

        //转化文件
        File excelFile = this.changeFile(multipartFile);

        //上传文件
        Long logId = SaveUpLoadFileToQiniu(excelFile);

        //查询日志
        RangeCalcLog rangeCalcLog = rangeCalcLogService.selectById(logId);

        if(Objects.nonNull(rangeCalcLog)){
            String key = rangeCalcLog.getUploadFileName();
            String file_url = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), key);

            try {

                String path = excelFile.getAbsolutePath();
                InputStream in = new FileInputStream(excelFile);
                /**
                 * 解析excel到对象
                 */
                Workbook wb = ImportExcelUtil.chooseWorkbook(path, in);
                Sheet sheet = wb.getSheetAt(0);

                /** 得到Excel的行数 */
                int totalRows = sheet.getPhysicalNumberOfRows();

                /** 判断是否超过1000 */
                if(totalRows > 1000){
                    throw new BaseException("上传的文件超过1000行，请重新上传！");
                }

                RangeXlsTemplate rangeXlsTemplate = new RangeXlsTemplate();

                //得到第一行
                List<RangeXlsTemplate> rangeList1 = ImportExcelUtil.readDataListT(wb,
                        rangeXlsTemplate, 1, totalRows-1);

                if(CollectionUtils.isEmpty(rangeList1)){
                    throw new BaseException("文件内容为空或者与模板不符合");
                }

                //判断文件格式
                RangeXlsTemplate item1 = rangeList1.get(0);
                if(Objects.isNull(item1) || StringUtils.isEmpty(item1.getOriginProvince()) || !item1.getOriginProvince().equals("起点省"))
                {
                    throw new BaseException("上传的文件格式与模板不符合");
                }

                List<RangeXlsTemplate> rangeList = ImportExcelUtil.readDataListT(wb,
                        rangeXlsTemplate, 2, 0);

                if(CollectionUtils.isEmpty(rangeList)){
                    throw new BaseException("文件内容为空");
                }

                for (int i = 0; i < rangeList.size(); i++) {
                    RangeXlsTemplate item = rangeList.get(i);
                    String origin = item.getOriginProvince() + item.getOriginCity() + item
                            .getOriginCounty() + item.getOriginAddress();
                    String dest = item.getDestProvince() + item.getDestCity() + item
                            .getDestCounty() + item.getDestAddress();
                    try{
                        double baiduRange = BaiDuMapRouteUtil.getDistance(origin, dest);
                        item.setBaiduRange(String.valueOf(baiduRange / 1000));
                    }catch(Exception ex){
//					logger.info("数据异常，异常原因：", ex.getMessage());
                        item.setBaiduRange("数据异常，异常原因："+ex.getMessage());
                    }
                }

                rangeCalcLog.setGmtFinishCalc(new Date());

                System.out.println("共导入数据【" + rangeList.size() + "】行");
                String[] columns ={"起点省","起点市","起点区","起点详细地址","终点省","终点市","终点区","终点详细地址","百度距离(KM)"};
                File fileExport = UriIOUtil.createFileByUrl(file_url, "xls");
                ExportExcelUtil exportExcelUtil = new ExportExcelUtil("路线计算",columns,rangeList,fileExport.getAbsolutePath());
                exportExcelUtil.export();
                String strDownload = this.SaveResultFileToQiniu(fileExport,rangeCalcLog);
                return rangeCalcLog.getId();

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
                LOGGER.error(ex.getMessage());
                rangeCalcLog.setCalcResult("导入计算失败，失败原因：" + ex.getMessage());
                rangeCalcLogService.updateById(rangeCalcLog);
                throw new BaseException(ex.getMessage());
            }
        }

        return null;
    }

    /**
     *  保存结果文件
     * @param file
     * @param rangeCalcLog
     */
    private String SaveResultFileToQiniu(File file,RangeCalcLog rangeCalcLog){
        String downloadUrl = null;
        try{
            String key = "template/" + file.getName();
            QuniuResponse quniuResponse = QiniuUtils.uploadFile(file,key);
            if(Objects.nonNull(quniuResponse)){
                rangeCalcLog.setResultFileName(key);
                rangeCalcLog.setCalcResult("success");
                rangeCalcLogService.updateById(rangeCalcLog);
            }
        }
        catch (Exception ex){
            rangeCalcLog.setCalcResult("导入计算失败，失败原因：" + ex.getMessage());
            rangeCalcLogService.updateById(rangeCalcLog);
            throw new BaseException(ex.getMessage());
        }

        return downloadUrl;
    }

    /**
     * 转化文件
     * @param file
     * @return
     */
    private File changeFile(MultipartFile file){
        try{
            //文件名
            String fileName = file.getOriginalFilename();
            // 获取文件后缀
            String suffix=fileName.substring(fileName.lastIndexOf("."));

            if(suffix.toUpperCase().contains("XLS") || suffix.toUpperCase().contains("XLSX")){
                //文件前缀
                String prefix=fileName.substring(0,fileName.lastIndexOf(".")-1);
                final File excelFile = File.createTempFile(prefix,suffix);
                // MultipartFile to File
                file.transferTo(excelFile);
                return excelFile;
            }
            else{
                throw new BaseException("请上传EXCEL文件!");
            }
        }
        catch (Exception ex){
            LOGGER.error(ex.getMessage());
            throw new BaseException(ex.getMessage());
        }
    }







}
